{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Document Research Assistant for Blog Creation\n",
    "\n",
    "[![ Click here to deploy.](https://brev-assets.s3.us-west-1.amazonaws.com/nv-lb-dark.svg)](https://console.brev.dev/launchable/deploy?launchableID=env-2qRrBuBdUGzzauhql87XCd7U1wR)\n",
    "\n",
    "Deploy with Launchables. Launchables are pre-configured, fully optimized environments that users can deploy with a single click.\n",
    "\n",
    "In this notebook, you will use an NVIDIA LLM NIM microservice (llama-3.3-70b) to generate a report on a given topic, and an NVIDIA NeMo Retriever embedding NIM (llama-3.2-nv-embedqa-1b-v2) for optimized text question-answering retrieval. Given a set of documents, LlamaIndex will create an Index which it can run queries against. \n",
    "\n",
    "You can get started by calling a hosted model's NIM API endpoint from the NVIDIA API catalog. Once you familiarize yourself with this blueprint, you may want to self-host models with NVIDIA NIM.\n",
    "\n",
    "The Blueprint provides a workflow architecture for automating and orchestrating the creation of well-researched, high-quality content. \n",
    "\n",
    "The user provides a set of tools (e.g., a query engine with data about San Francisco's budget) and a content request (e.g., a question for a blog post). The Agent then:\n",
    "1. Generates an Outline: Deploys an agent to structure the blog post into an actionable outline.\n",
    "2. Plans Research Questions: Another agent generates a list of questions necessary to address the outline effectively.\n",
    "3. Parallel Research: Breaks the questions into discrete units that can be answered concurrently, using available tools for data collection.\n",
    "4. Drafts the Content: A writer agent synthesizes the gathered answers into a cohesive blog post.\n",
    "5. Performs Quality Assurance: A critic agent reviews the content for accuracy, coherence, and completeness, determining if revisions are necessary.\n",
    "6. Iterative Refinement: If improvements are needed, the workflow repeats by generating additional questions and gathering more information until the desired quality is reached.\n",
    "\n",
    "This workflow combines modularity, automation, and iterative refinement to ensure the output meets the highest standards of quality. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image]()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Content Overview\n",
    ">[Prerequisites](#Prerequisites)  \n",
    ">[Create New Index from Document](#Create-New-Index-from-Document)  \n",
    ">[Create Engine Query Tool](#Create-Engine-Query-Tool)  \n",
    ">[Build the Agent](#Build-the-Agent)  \n",
    ">[Test the Agent](#Test-the-Agent)  \n",
    "________________________"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "\n",
    "### Install Dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install llama-index-core\n",
    "!pip install llama-index-core\n",
    "!pip install llama-index-llms-nvidia\n",
    "!pip install llama-index-embeddings-nvidia\n",
    "!pip install llama-index-utils-workflow\n",
    "!pip install llama-parse"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If your environment does not have `wget` , make sure to install that as well."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download data\n",
    "\n",
    "The data for this notebook is the City of San Francisco's Proposed Budget."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!wget \"https://www.dropbox.com/scl/fi/vip161t63s56vd94neqlt/2023-CSF_Proposed_Budget_Book_June_2023_Master_Web.pdf?rlkey=hemoce3w1jsuf6s2bz87g549i&dl=0\" -O \"san_francisco_budget_2023.pdf\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# llama-parse is async-first, running the async code in a notebook requires the use of nest_asyncio\n",
    "import nest_asyncio\n",
    "\n",
    "nest_asyncio.apply()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## API Keys\n",
    "Prior to getting started, you will need to create API Keys for the NVIDIA API Catalog if you're not self-hosting a model and LlamaIndex to use LlamaCloud. \n",
    "\n",
    "- NVIDIA API Catalog\n",
    "  1. Navigate to **[NVIDIA API Catalog](https://build.nvidia.com/explore/discover)**.\n",
    "  2. Select any model, such as llama-3.3-70b-instruct.\n",
    "  3. On the right panel above the sample code snippet, click on \"Get API Key\". This will prompt you to log in if you have not already.\n",
    "- LlamaIndex\n",
    "  1. Go to **[LlamaIndex login page](https://cloud.llamaindex.ai/login)**. You will need to create an account if you have not already.\n",
    "  2. On the left panel, navigate to \"API Key\".\n",
    "  3. Click on the \"Generate New Key\" on the top of the page.\n",
    "\n",
    "### Export API Keys\n",
    "\n",
    "Save these API Keys as environment variables."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, set the NVIDIA API Key as the environment variable. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\n",
    "\n",
    "if not os.environ.get(\"NVIDIA_API_KEY\", \"\").startswith(\"nvapi-\"):\n",
    "    nvapi_key = getpass.getpass(\"Enter your NVIDIA API key: \")\n",
    "    assert nvapi_key.startswith(\n",
    "        \"nvapi-\"\n",
    "    ), f\"{nvapi_key[:5]}... is not a valid key\"\n",
    "    os.environ[\"NVIDIA_API_KEY\"] = nvapi_key"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, set the LlamaIndex API Key for LlamaCloud."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os, getpass\n",
    "\n",
    "\n",
    "def _set_env(var: str):\n",
    "    if not os.environ.get(var):\n",
    "        os.environ[var] = getpass.getpass(f\"{var}: \")\n",
    "\n",
    "\n",
    "_set_env(\"LLAMA_CLOUD_API_KEY\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Working with the NVIDIA API Catalog\n",
    "Let's test the API endpoint.\n",
    "\n",
    "We'll use both an LLM and embedding model in this notebook so we'll import both the packages now. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "assistant: The most popular house pets in North America are dogs, cats, fish, birds, and small mammals such as hamsters, guinea pigs, and rabbits, with dogs and cats being the clear favorites among pet owners.\n"
     ]
    }
   ],
   "source": [
    "from llama_index.embeddings.nvidia import NVIDIAEmbedding\n",
    "from llama_index.llms.nvidia import NVIDIA\n",
    "from llama_index.core.llms import ChatMessage, MessageRole\n",
    "\n",
    "llm = NVIDIA(model=\"meta/llama-3.3-70b-instruct\")\n",
    "\n",
    "messages = [\n",
    "    ChatMessage(\n",
    "        role=MessageRole.SYSTEM,\n",
    "        content=(\"You are a helpful assistant that answers in one sentence.\"),\n",
    "    ),\n",
    "    ChatMessage(\n",
    "        role=MessageRole.USER,\n",
    "        content=(\"What are the most popular house pets in North America?\"),\n",
    "    ),\n",
    "]\n",
    "\n",
    "response = llm.chat(messages)\n",
    "\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Optional: Locally Run NVIDIA NIM Microservices\n",
    "\n",
    "Once you familiarize yourself with this blueprint, you may want to self-host models with NVIDIA NIM Microservices using NVIDIA AI Enterprise software license. This gives you the ability to run models anywhere, giving you ownership of your customizations and full control of your intellectual property (IP) and AI applications.\n",
    "\n",
    "[Learn more about NIM Microservices](https://developer.nvidia.com/blog/nvidia-nim-offers-optimized-inference-microservices-for-deploying-ai-models-at-scale/)\n",
    "\n",
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>NOTE:</b> Run the following cell only if you're using a local NIM Microservice instead of the API Catalog Endpoint.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.nvidia import NVIDIA\n",
    "from llama_index.core import Settings\n",
    "\n",
    "# connect to an LLM NIM running at localhost:8000, specifying a model\n",
    "Settings.llm = NVIDIA(\n",
    "    base_url=\"http://localhost:8000/v1\", model=\"meta/llama-3.3-70b-instruct\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Set LLM and Embedding Model\n",
    "\n",
    "In this notebook, you will use the newest llama model, llama-3.3-70b-instruct, as the LLM.\n",
    "You will also use NVIDIA's embedding model, llama-3.2-nv-embedqa-1b-v2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core import Settings\n",
    "\n",
    "Settings.llm = NVIDIA(model=\"meta/llama-3.3-70b-instruct\")\n",
    "Settings.embed_model = NVIDIAEmbedding(\n",
    "    model=\"nvidia/llama-3.2-nv-embedqa-1b-v2\", truncate=\"END\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create New Index from Document"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core import (\n",
    "    VectorStoreIndex,\n",
    "    StorageContext,\n",
    "    load_index_from_storage,\n",
    ")\n",
    "from llama_parse import LlamaParse\n",
    "\n",
    "DATA_DIR = \"./data\"\n",
    "PERSIST_DIR = \"./storage\"\n",
    "\n",
    "if os.path.exists(PERSIST_DIR):\n",
    "    print(\"Loading existing index...\")\n",
    "    storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)\n",
    "    index = load_index_from_storage(storage_context)\n",
    "else:\n",
    "    print(\"Creating new index...\")\n",
    "\n",
    "    file_path = \"./san_francisco_budget_2023.pdf\"\n",
    "\n",
    "    documents = LlamaParse(result_type=\"markdown\").load_data(file_path)\n",
    "\n",
    "    index = VectorStoreIndex.from_documents(documents)\n",
    "    index.storage_context.persist(persist_dir=PERSIST_DIR)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Run a Query Against the Index\n",
    "Create a Query engine from the Index. A Query Engine is a generic interface that allows you to ask question over your data.\n",
    "Here, the parameter `similarity_top_k` is set to 10. If you are using your own documents, you can play around with this parameter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The proposed Fiscal Year 2023-24 budget for the Police Department is $776.8 million.\n"
     ]
    }
   ],
   "source": [
    "query_engine = index.as_query_engine(similarity_top_k=10)\n",
    "response = query_engine.query(\n",
    "    \"What was San Francisco's budget for Police in 2023?\"\n",
    ")\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create Engine Query Tool\n",
    "Next, create a Query Engine Tool. This takes the Query Engine defined earlier and wraps it as a tool the Agent can use. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.tools import QueryEngineTool\n",
    "\n",
    "budget_tool = QueryEngineTool.from_defaults(\n",
    "    query_engine,\n",
    "    name=\"san_francisco_budget_2023\",\n",
    "    description=\"A RAG engine with extremely detailed information about the 2023 San Francisco budget.\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Build the Agent\n",
    "\n",
    "The workflow is:\n",
    "* you give it a set of tools (in this case it's  a query engine with data about SF's budget)\n",
    "* you give it a question to write a blog post about\n",
    "* one agent generates an outline of what the blog post should look like\n",
    "* the next generates a list of questions that would be necessary to gather data to fulfill that outline\n",
    "* the questions are split up and answered concurrently\n",
    "* a writer collects the questions and answers and writes a blog post\n",
    "* a critic reviews the blog post and determines if it needs more work\n",
    "  * if it's fine, the workflow stops\n",
    "  * if it needs more work, it generates additional questions\n",
    "  * those questions are answered and the process repeats"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "from llama_index.core.workflow import (\n",
    "    step,\n",
    "    Event,\n",
    "    Context,\n",
    "    StartEvent,\n",
    "    StopEvent,\n",
    "    Workflow,\n",
    ")\n",
    "from llama_index.core.agent.workflow import FunctionAgent\n",
    "\n",
    "\n",
    "class OutlineEvent(Event):\n",
    "    outline: str\n",
    "\n",
    "\n",
    "class QuestionEvent(Event):\n",
    "    question: str\n",
    "\n",
    "\n",
    "class AnswerEvent(Event):\n",
    "    question: str\n",
    "    answer: str\n",
    "\n",
    "\n",
    "class ReviewEvent(Event):\n",
    "    report: str\n",
    "\n",
    "\n",
    "class ProgressEvent(Event):\n",
    "    progress: str\n",
    "\n",
    "\n",
    "class DocumentResearchAgent(Workflow):\n",
    "    # get the initial request and create an outline of the blog post knowing nothing about the topic\n",
    "    @step\n",
    "    async def formulate_plan(\n",
    "        self, ctx: Context, ev: StartEvent\n",
    "    ) -> OutlineEvent:\n",
    "        query = ev.query\n",
    "        await ctx.store.set(\"original_query\", query)\n",
    "        await ctx.store.set(\"tools\", ev.tools)\n",
    "\n",
    "        prompt = f\"\"\"You are an expert at writing blog posts. You have been given a topic to write\n",
    "        a blog post about. Plan an outline for the blog post; it should be detailed and specific.\n",
    "        Another agent will formulate questions to find the facts necessary to fulfill the outline.\n",
    "        The topic is: {query}\"\"\"\n",
    "\n",
    "        response = await Settings.llm.acomplete(prompt)\n",
    "\n",
    "        ctx.write_event_to_stream(\n",
    "            ProgressEvent(progress=\"Outline:\\n\" + str(response))\n",
    "        )\n",
    "\n",
    "        return OutlineEvent(outline=str(response))\n",
    "\n",
    "    # formulate some questions based on the outline\n",
    "    @step\n",
    "    async def formulate_questions(\n",
    "        self, ctx: Context, ev: OutlineEvent\n",
    "    ) -> QuestionEvent:\n",
    "        outline = ev.outline\n",
    "        await ctx.store.set(\"outline\", outline)\n",
    "\n",
    "        prompt = f\"\"\"You are an expert at formulating research questions. You have been given an outline\n",
    "        for a blog post. Formulate a series of simple questions that will get you the facts necessary\n",
    "        to fulfill the outline. You cannot assume any existing knowledge; you must ask at least one\n",
    "        question for every bullet point in the outline. Avoid complex or multi-part questions; break\n",
    "        them down into a series of simple questions. Your output should be a list of questions, each\n",
    "        on a new line. Do not include headers or categories or any preamble or explanation; just a\n",
    "        list of questions. For speed of response, limit yourself to 8 questions. The outline is: {outline}\"\"\"\n",
    "\n",
    "        response = await Settings.llm.acomplete(prompt)\n",
    "\n",
    "        questions = str(response).split(\"\\n\")\n",
    "        questions = [x for x in questions if x]\n",
    "\n",
    "        ctx.write_event_to_stream(\n",
    "            ProgressEvent(\n",
    "                progress=\"Formulated questions:\\n\" + \"\\n\".join(questions)\n",
    "            )\n",
    "        )\n",
    "\n",
    "        await ctx.store.set(\"num_questions\", len(questions))\n",
    "\n",
    "        ctx.write_event_to_stream(\n",
    "            ProgressEvent(progress=\"Questions:\\n\" + \"\\n\".join(questions))\n",
    "        )\n",
    "\n",
    "        for question in questions:\n",
    "            ctx.send_event(QuestionEvent(question=question))\n",
    "\n",
    "    # answer each question in turn\n",
    "    @step\n",
    "    async def answer_question(\n",
    "        self, ctx: Context, ev: QuestionEvent\n",
    "    ) -> AnswerEvent:\n",
    "        question = ev.question\n",
    "        if (\n",
    "            not question\n",
    "            or question.isspace()\n",
    "            or question == \"\"\n",
    "            or question is None\n",
    "        ):\n",
    "            ctx.write_event_to_stream(\n",
    "                ProgressEvent(progress=f\"Skipping empty question.\")\n",
    "            )  # Log skipping empty question\n",
    "            return None\n",
    "        agent = FunctionAgent(\n",
    "            tools=await ctx.store.get(\"tools\"),\n",
    "            llm=Settings.llm,\n",
    "        )\n",
    "        response = await agent.run(question)\n",
    "        response = str(response)\n",
    "\n",
    "        ctx.write_event_to_stream(\n",
    "            ProgressEvent(\n",
    "                progress=f\"To question '{question}' the agent answered: {response}\"\n",
    "            )\n",
    "        )\n",
    "\n",
    "        return AnswerEvent(question=question, answer=response)\n",
    "\n",
    "    # given all the answers to all the questions and the outline, write the blog poost\n",
    "    @step\n",
    "    async def write_report(self, ctx: Context, ev: AnswerEvent) -> ReviewEvent:\n",
    "        # wait until we receive as many answers as there are questions\n",
    "        num_questions = await ctx.store.get(\"num_questions\")\n",
    "        results = ctx.collect_events(ev, [AnswerEvent] * num_questions)\n",
    "        if results is None:\n",
    "            return None\n",
    "\n",
    "        # maintain a list of all questions and answers no matter how many times this step is called\n",
    "        try:\n",
    "            previous_questions = await ctx.store.get(\"previous_questions\")\n",
    "        except:\n",
    "            previous_questions = []\n",
    "        previous_questions.extend(results)\n",
    "        await ctx.store.set(\"previous_questions\", previous_questions)\n",
    "\n",
    "        prompt = f\"\"\"You are an expert at writing blog posts. You are given an outline of a blog post\n",
    "        and a series of questions and answers that should provide all the data you need to write the\n",
    "        blog post. Compose the blog post according to the outline, using only the data given in the\n",
    "        answers. The outline is in <outline> and the questions and answers are in <questions> and\n",
    "        <answers>.\n",
    "        <outline>{await ctx.store.get('outline')}</outline>\"\"\"\n",
    "\n",
    "        for result in previous_questions:\n",
    "            prompt += f\"<question>{result.question}</question>\\n<answer>{result.answer}</answer>\\n\"\n",
    "\n",
    "        ctx.write_event_to_stream(\n",
    "            ProgressEvent(progress=\"Writing report with prompt:\\n\" + prompt)\n",
    "        )\n",
    "\n",
    "        report = await Settings.llm.acomplete(prompt)\n",
    "\n",
    "        return ReviewEvent(report=str(report))\n",
    "\n",
    "    # review the report. If it still needs work, formulate some more questions.\n",
    "    @step\n",
    "    async def review_report(\n",
    "        self, ctx: Context, ev: ReviewEvent\n",
    "    ) -> StopEvent | QuestionEvent:\n",
    "        # we re-review a maximum of 3 times\n",
    "        try:\n",
    "            num_reviews = await ctx.store.get(\"num_reviews\")\n",
    "        except:\n",
    "            num_reviews = 1\n",
    "        num_reviews += 1\n",
    "        await ctx.store.set(\"num_reviews\", num_reviews)\n",
    "\n",
    "        report = ev.report\n",
    "\n",
    "        prompt = f\"\"\"You are an expert reviewer of blog posts. You are given an original query,\n",
    "        and a blog post that was written to satisfy that query. Review the blog post and determine\n",
    "        if it adequately answers the query and contains enough detail. If it doesn't, come up with\n",
    "        a set of questions that will get you the facts necessary to expand the blog post. Another\n",
    "        agent will answer those questions. Your response should just be a list of questions, one\n",
    "        per line, without any preamble or explanation. For speed, generate a maximum of 4 questions.\n",
    "        The original query is: '{await ctx.store.get('original_query')}'.\n",
    "        The blog post is: <blogpost>{report}</blogpost>.\n",
    "        If the blog post is fine, return just the string 'OKAY'.\"\"\"\n",
    "\n",
    "        response = await Settings.llm.acomplete(prompt)\n",
    "\n",
    "        if response == \"OKAY\" or await ctx.store.get(\"num_reviews\") >= 3:\n",
    "            ctx.write_event_to_stream(\n",
    "                ProgressEvent(progress=\"Blog post is fine\")\n",
    "            )\n",
    "            return StopEvent(result=report)\n",
    "        else:\n",
    "            questions = str(response).split(\"\\n\")\n",
    "            await ctx.store.set(\"num_questions\", len(questions))\n",
    "            ctx.write_event_to_stream(\n",
    "                ProgressEvent(progress=\"Formulated some more questions\")\n",
    "            )\n",
    "            for question in questions:\n",
    "                ctx.send_event(QuestionEvent(question=question))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test the Agent\n",
    "\n",
    "Run the Agent with a query and look at the generated blog post written to answer it"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running step formulate_plan\n",
      "Step formulate_plan produced event OutlineEvent\n",
      "Outline:\n",
      "Here is a detailed outline for the blog post on the budget of the San Francisco Police Department in 2023:\n",
      "\n",
      "**I. Introduction**\n",
      "\n",
      "* Brief overview of the San Francisco Police Department (SFPD) and its role in the city\n",
      "* Importance of understanding the budget of the SFPD\n",
      "* Thesis statement: The 2023 budget of the San Francisco Police Department is a critical component of the city's public safety strategy, and understanding its allocation and priorities is essential for ensuring effective policing and community safety.\n",
      "\n",
      "**II. Overview of the 2023 Budget**\n",
      "\n",
      "* Total budget allocation for the SFPD in 2023\n",
      "* Comparison to previous years' budgets (e.g., 2022, 2021)\n",
      "* Breakdown of the budget into major categories (e.g., personnel, operations, equipment, training)\n",
      "\n",
      "**III. Personnel Costs**\n",
      "\n",
      "* Salary and benefits for sworn officers and civilian staff\n",
      "* Number of personnel and staffing levels\n",
      "* Recruitment and retention strategies and their associated costs\n",
      "* Discussion of any notable changes or trends in personnel costs (e.g., increased overtime, hiring freezes)\n",
      "\n",
      "**IV. Operational Expenses**\n",
      "\n",
      "* Overview of operational expenses, including:\n",
      "\t+ Fuel and vehicle maintenance\n",
      "\t+ Equipment and supplies (e.g., firearms, body armor, communication devices)\n",
      "\t+ Facility maintenance and utilities\n",
      "\t+ Travel and training expenses\n",
      "* Discussion of any notable changes or trends in operational expenses (e.g., increased fuel costs, new equipment purchases)\n",
      "\n",
      "**V. Community Policing and Outreach Initiatives**\n",
      "\n",
      "* Overview of community policing and outreach initiatives, including:\n",
      "\t+ Neighborhood policing programs\n",
      "\t+ Youth and community engagement programs\n",
      "\t+ Mental health and crisis response services\n",
      "* Budget allocation for these initiatives and discussion of their effectiveness\n",
      "\n",
      "**VI. Technology and Equipment Upgrades**\n",
      "\n",
      "* Overview of technology and equipment upgrades, including:\n",
      "\t+ Body-worn cameras and other surveillance technology\n",
      "\t+ Communication systems and emergency response infrastructure\n",
      "\t+ Forensic analysis and crime lab equipment\n",
      "* Budget allocation for these upgrades and discussion of their impact on policing and public safety\n",
      "\n",
      "**VII. Challenges and Controversies**\n",
      "\n",
      "* Discussion of challenges and controversies related to the SFPD budget, including:\n",
      "\t+ Funding for police reform and accountability initiatives\n",
      "\t+ Criticisms of police spending and resource allocation\n",
      "\t+ Impact of budget constraints on policing services and community safety\n",
      "\n",
      "**VIII. Conclusion**\n",
      "\n",
      "* Summary of key findings and takeaways from the 2023 SFPD budget\n",
      "* Discussion of implications for public safety and community policing in San Francisco\n",
      "* Final thoughts and recommendations for future budget allocations and policing strategies.\n",
      "\n",
      "To fulfill this outline, the following questions will need to be answered:\n",
      "\n",
      "* What is the total budget allocation for the SFPD in 2023?\n",
      "* How does the 2023 budget compare to previous years' budgets?\n",
      "* What are the major categories of expenditure in the 2023 budget?\n",
      "* What are the personnel costs, including salary and benefits, for sworn officers and civilian staff?\n",
      "* What are the operational expenses, including fuel, equipment, and facility maintenance?\n",
      "* What community policing and outreach initiatives are funded in the 2023 budget?\n",
      "* What technology and equipment upgrades are planned or underway, and what is their budget allocation?\n",
      "* What challenges and controversies are associated with the SFPD budget, and how are they being addressed?\n",
      "\n",
      "These questions will help to gather the necessary facts and information to create a comprehensive and informative blog post on the budget of the San Francisco Police Department in 2023.\n",
      "Running step formulate_questions\n",
      "Step formulate_questions produced no event\n",
      "Formulated questions:\n",
      "What is the total budget allocation for the SFPD in 2023?\n",
      "How does the 2023 budget compare to the 2022 budget?\n",
      "What are the major categories of expenditure in the 2023 budget?\n",
      "What are the personnel costs, including salary and benefits, for sworn officers?\n",
      "What are the operational expenses, including fuel and vehicle maintenance?\n",
      "What community policing and outreach initiatives are funded in the 2023 budget?\n",
      "What technology and equipment upgrades are planned or underway?\n",
      "What challenges and controversies are associated with the SFPD budget?\n",
      "Questions:\n",
      "What is the total budget allocation for the SFPD in 2023?\n",
      "How does the 2023 budget compare to the 2022 budget?\n",
      "What are the major categories of expenditure in the 2023 budget?\n",
      "What are the personnel costs, including salary and benefits, for sworn officers?\n",
      "What are the operational expenses, including fuel and vehicle maintenance?\n",
      "What community policing and outreach initiatives are funded in the 2023 budget?\n",
      "What technology and equipment upgrades are planned or underway?\n",
      "What challenges and controversies are associated with the SFPD budget?\n",
      "Running step answer_question\n",
      "> Running step d0e11f46-4071-43aa-9f06-0ddffe477928. Step input: What is the total budget allocation for the SFPD in 2023?\n",
      "Added user message to memory: What is the total budget allocation for the SFPD in 2023?\n",
      "Running step answer_question\n",
      "> Running step 44ded067-ea4c-4575-97b2-5fbaf444b189. Step input: How does the 2023 budget compare to the 2022 budget?\n",
      "Added user message to memory: How does the 2023 budget compare to the 2022 budget?\n",
      "Running step answer_question\n",
      "> Running step 28b603af-894b-4654-949d-48340149d8e8. Step input: What are the major categories of expenditure in the 2023 budget?\n",
      "Added user message to memory: What are the major categories of expenditure in the 2023 budget?\n",
      "Running step answer_question\n",
      "> Running step 5c6a5ebb-3787-4401-a5e3-aa93e03d1832. Step input: What are the personnel costs, including salary and benefits, for sworn officers?\n",
      "Added user message to memory: What are the personnel costs, including salary and benefits, for sworn officers?\n",
      "=== Calling Function ===\n",
      "Calling function: san_francisco_budget_2023 with args: {\"input\": \"SFPD total budget allocation 2023\"}\n",
      "=== LLM Response ===\n",
      "<function:san_francisco_budget_2023>{\"input\": \"personnel costs for sworn officers\"}</function>\n",
      "Step answer_question produced event AnswerEvent\n",
      "Running step answer_question\n",
      "> Running step 3853365e-fd6d-498d-b92f-25f8969ffe43. Step input: What are the operational expenses, including fuel and vehicle maintenance?\n",
      "Added user message to memory: What are the operational expenses, including fuel and vehicle maintenance?\n",
      "To question 'What are the personnel costs, including salary and benefits, for sworn officers?' the agent answered: <function:san_francisco_budget_2023>{\"input\": \"personnel costs for sworn officers\"}</function>\n",
      "Running step write_report\n",
      "Step write_report produced no event\n",
      "=== Calling Function ===\n",
      "Calling function: san_francisco_budget_2023 with args: {\"input\": \"major categories of expenditure in the 2023 budget\"}\n",
      "=== LLM Response ===\n",
      "<function:san_francisco_budget_2023>{\"input\": \"compare 2023 budget to 2022 budget\"}</function>\n",
      "Step answer_question produced event AnswerEvent\n",
      "Running step answer_question\n",
      "> Running step 4487ccea-3e7e-4378-b299-a5372dbc6aaf. Step input: What community policing and outreach initiatives are funded in the 2023 budget?\n",
      "Added user message to memory: What community policing and outreach initiatives are funded in the 2023 budget?\n",
      "To question 'How does the 2023 budget compare to the 2022 budget?' the agent answered: <function:san_francisco_budget_2023>{\"input\": \"compare 2023 budget to 2022 budget\"}</function>\n",
      "Running step write_report\n",
      "Step write_report produced no event\n",
      "=== Calling Function ===\n",
      "Calling function: san_francisco_budget_2023 with args: {\"input\": \"operational expenses, including fuel and vehicle maintenance\"}\n",
      "=== LLM Response ===\n",
      "<function:san_francisco_budget_2023>{\"input\": \"community policing and outreach initiatives 2023 budget\"}</function>\n",
      "Step answer_question produced event AnswerEvent\n",
      "Running step answer_question\n",
      "> Running step 75022818-5d76-4443-b3c6-c5558991713c. Step input: What technology and equipment upgrades are planned or underway?\n",
      "Added user message to memory: What technology and equipment upgrades are planned or underway?\n",
      "To question 'What community policing and outreach initiatives are funded in the 2023 budget?' the agent answered: <function:san_francisco_budget_2023>{\"input\": \"community policing and outreach initiatives 2023 budget\"}</function>\n",
      "Running step write_report\n",
      "Step write_report produced no event\n",
      "=== Calling Function ===\n",
      "Calling function: san_francisco_budget_2023 with args: {\"input\": \"technology and equipment upgrades planned or underway\"}\n",
      "=== Function Output ===\n",
      "The query is asking for the SFPD total budget allocation for 2023, but the provided context does not mention the SFPD's budget for 2023. It discusses the budgets of the Juvenile Probation Department and the Public Utilities Commission. Therefore, the original answer cannot be rewritten with the new context, and the original answer should be repeated. \n",
      "\n",
      "The total budget allocation for the San Francisco Police Department (SFPD) in 2023 is $776.8 million.\n",
      "> Running step 927d5844-8c20-4cc8-a50f-52248963206f. Step input: None\n",
      "=== LLM Response ===\n",
      "The total budget allocation for the San Francisco Police Department (SFPD) in 2023 is $776.8 million.\n",
      "Step answer_question produced event AnswerEvent\n",
      "Running step answer_question\n",
      "> Running step 0dcc7a13-046a-4259-96eb-7a2817530875. Step input: What challenges and controversies are associated with the SFPD budget?\n",
      "Added user message to memory: What challenges and controversies are associated with the SFPD budget?\n",
      "To question 'What is the total budget allocation for the SFPD in 2023?' the agent answered: The total budget allocation for the San Francisco Police Department (SFPD) in 2023 is $776.8 million.\n",
      "Running step write_report\n",
      "Step write_report produced no event\n",
      "=== Calling Function ===\n",
      "Calling function: san_francisco_budget_2023 with args: {\"input\": \"SFPD budget challenges and controversies\"}\n",
      "=== Function Output ===\n",
      "Non-Personnel Services, which includes expenses such as fuel and vehicle maintenance, has a budget of $1,088,786,650 for 2024-2025, showing a continued significant allocation for operational expenses. This category likely encompasses a broad range of expenditures related to the upkeep and operation of vehicles and other equipment, underscoring the organization's ongoing commitment to maintaining its assets and ensuring their continued functionality.\n",
      "> Running step a55db034-f7ba-4e87-960e-0605574c3398. Step input: None\n",
      "=== LLM Response ===\n",
      "The operational expenses, including fuel and vehicle maintenance, have a budget of $1,088,786,650 for 2024-2025. This category likely encompasses a broad range of expenditures related to the upkeep and operation of vehicles and other equipment, underscoring the organization's ongoing commitment to maintaining its assets and ensuring their continued functionality.\n",
      "Step answer_question produced event AnswerEvent\n",
      "To question 'What are the operational expenses, including fuel and vehicle maintenance?' the agent answered: The operational expenses, including fuel and vehicle maintenance, have a budget of $1,088,786,650 for 2024-2025. This category likely encompasses a broad range of expenditures related to the upkeep and operation of vehicles and other equipment, underscoring the organization's ongoing commitment to maintaining its assets and ensuring their continued functionality.\n",
      "Running step write_report\n",
      "Step write_report produced no event\n",
      "=== Function Output ===\n",
      "Several technology and equipment upgrades are planned or underway. The City is investing in vital technology projects, including the replacement of critical systems and the development of new platforms to enhance city services and operations. The City's focus on cloud solutions continues, with efforts to expand and optimize cloud services, including the provisioning of Infrastructure-as-a-Service (IaaS) and Platform-as-a-Service (PaaS) to support daily operations. Additionally, the City is working on initiatives to improve digital accessibility and inclusion, and to develop new applications that enhance the speed, security, performance, and reliability of City services. The establishment of centers of excellence, such as the Cloud Center of Excellence, aims to help departments leverage technology more effectively and efficiently. Furthermore, the City is exploring new technologies and solutions to support its goals, including the development of online portals and databases to facilitate resident engagement and access to city services.\n",
      "> Running step f34e8f8a-9c59-4e02-9394-a8293ff24af6. Step input: None\n",
      "=== LLM Response ===\n",
      "The City of San Francisco is planning or undertaking various technology and equipment upgrades. These include replacing critical systems, developing new platforms to enhance city services and operations, expanding and optimizing cloud services, improving digital accessibility and inclusion, and developing new applications to enhance the speed, security, performance, and reliability of City services. Additionally, the City is establishing centers of excellence, such as the Cloud Center of Excellence, to help departments leverage technology more effectively and efficiently. The City is also exploring new technologies and solutions to support its goals, including the development of online portals and databases to facilitate resident engagement and access to city services.\n",
      "Step answer_question produced event AnswerEvent\n",
      "To question 'What technology and equipment upgrades are planned or underway?' the agent answered: The City of San Francisco is planning or undertaking various technology and equipment upgrades. These include replacing critical systems, developing new platforms to enhance city services and operations, expanding and optimizing cloud services, improving digital accessibility and inclusion, and developing new applications to enhance the speed, security, performance, and reliability of City services. Additionally, the City is establishing centers of excellence, such as the Cloud Center of Excellence, to help departments leverage technology more effectively and efficiently. The City is also exploring new technologies and solutions to support its goals, including the development of online portals and databases to facilitate resident engagement and access to city services.\n",
      "Running step write_report\n",
      "Step write_report produced no event\n",
      "=== Function Output ===\n",
      "The major categories of expenditure in the 2023 budget include citywide expenditures such as voter mandated General Fund support for transit, libraries, and other baselines, the General Fund portion of retiree health premiums, nonprofit cost of doing business increases, required reserve deposits, and debt service. These costs are budgeted in General City Responsibility rather than allocating costs to departments. Additionally, expenditures related to Human Welfare & Neighborhood Development are also significant, including departments such as Children, Youth & Their Families, Child Support Services, Dept of Early Childhood, Environment, Homelessness And Supportive Housing, Human Rights Commission, and Human Services.\n",
      "> Running step 1b1640ad-977c-423d-b88d-e9cf4de53e5b. Step input: None\n",
      "=== LLM Response ===\n",
      "The major categories of expenditure in the 2023 budget include citywide expenditures such as voter mandated General Fund support for transit, libraries, and other baselines, the General Fund portion of retiree health premiums, nonprofit cost of doing business increases, required reserve deposits, and debt service. These costs are budgeted in General City Responsibility rather than allocating costs to departments. Additionally, expenditures related to Human Welfare & Neighborhood Development are also significant, including departments such as Children, Youth & Their Families, Child Support Services, Dept of Early Childhood, Environment, Homelessness And Supportive Housing, Human Rights Commission, and Human Services.\n",
      "Step answer_question produced event AnswerEvent\n",
      "To question 'What are the major categories of expenditure in the 2023 budget?' the agent answered: The major categories of expenditure in the 2023 budget include citywide expenditures such as voter mandated General Fund support for transit, libraries, and other baselines, the General Fund portion of retiree health premiums, nonprofit cost of doing business increases, required reserve deposits, and debt service. These costs are budgeted in General City Responsibility rather than allocating costs to departments. Additionally, expenditures related to Human Welfare & Neighborhood Development are also significant, including departments such as Children, Youth & Their Families, Child Support Services, Dept of Early Childhood, Environment, Homelessness And Supportive Housing, Human Rights Commission, and Human Services.\n",
      "Running step write_report\n",
      "Step write_report produced no event\n",
      "=== Function Output ===\n",
      "The San Francisco Police Department (SFPD) faces significant budget challenges, including recruitment and retention issues, with staffing levels continuing to fall behind recommended levels as separations have outpaced recruiting. The Department is also dealing with chronic understaffing, which requires overtime funding support to ensure necessary deployment levels. Furthermore, the SFPD is working to implement reforms and achieve substantial compliance with state laws, including SB 1421, SB 16, and SB 2, which requires investments in information technology, training, and other resources.\n",
      "\n",
      "In the context of project spending, the SFPD's budget challenges are exacerbated by the need to allocate resources for various projects, such as technology upgrades, training programs, and community initiatives. The Department must balance these competing demands and priorities to ensure effective and responsible use of its budget. Controversies surrounding the SFPD budget may include the use of overtime funding, the implementation of new technologies and systems, and the allocation of resources for community programs and initiatives. The Department's efforts to address issues of trust and accountability within the community, particularly in light of the need for periodic biased policing audits, may also be a subject of controversy and debate. Additionally, the budget's focus on increasing salaries and benefits for sworn staff, as well as the expansion of programs aimed at improving community relations, may be seen as contentious by some stakeholders. \n",
      "\n",
      "Given the projected deficit, the Mayor's requirement for departments to propose budget reductions may impact the SFPD's ability to allocate resources for these projects, potentially affecting the Department's ability to implement reforms and achieve its goals. The SFPD must navigate these challenges and controversies to ensure effective and responsible use of its budget, while also addressing the needs and concerns of the community.\n",
      "> Running step 3ba46541-2a08-446a-b3fc-2c3df3be814f. Step input: None\n",
      "=== LLM Response ===\n",
      "The San Francisco Police Department (SFPD) faces significant budget challenges, including recruitment and retention issues, chronic understaffing, and the need to implement reforms and achieve substantial compliance with state laws. The Department must balance competing demands and priorities to ensure effective and responsible use of its budget. Controversies surrounding the SFPD budget may include the use of overtime funding, the implementation of new technologies and systems, and the allocation of resources for community programs and initiatives. The Department's efforts to address issues of trust and accountability within the community may also be a subject of controversy and debate.\n",
      "Step answer_question produced event AnswerEvent\n",
      "To question 'What challenges and controversies are associated with the SFPD budget?' the agent answered: The San Francisco Police Department (SFPD) faces significant budget challenges, including recruitment and retention issues, chronic understaffing, and the need to implement reforms and achieve substantial compliance with state laws. The Department must balance competing demands and priorities to ensure effective and responsible use of its budget. Controversies surrounding the SFPD budget may include the use of overtime funding, the implementation of new technologies and systems, and the allocation of resources for community programs and initiatives. The Department's efforts to address issues of trust and accountability within the community may also be a subject of controversy and debate.\n",
      "Running step write_report\n",
      "Writing report with prompt:\n",
      "You are an expert at writing blog posts. You are given an outline of a blog post\n",
      "        and a series of questions and answers that should provide all the data you need to write the\n",
      "        blog post. Compose the blog post according to the outline, using only the data given in the\n",
      "        answers. The outline is in <outline> and the questions and answers are in <questions> and\n",
      "        <answers>.\n",
      "        <outline>Here is a detailed outline for the blog post on the budget of the San Francisco Police Department in 2023:\n",
      "\n",
      "**I. Introduction**\n",
      "\n",
      "* Brief overview of the San Francisco Police Department (SFPD) and its role in the city\n",
      "* Importance of understanding the budget of the SFPD\n",
      "* Thesis statement: The 2023 budget of the San Francisco Police Department is a critical component of the city's public safety strategy, and understanding its allocation and priorities is essential for ensuring effective policing and community safety.\n",
      "\n",
      "**II. Overview of the 2023 Budget**\n",
      "\n",
      "* Total budget allocation for the SFPD in 2023\n",
      "* Comparison to previous years' budgets (e.g., 2022, 2021)\n",
      "* Breakdown of the budget into major categories (e.g., personnel, operations, equipment, training)\n",
      "\n",
      "**III. Personnel Costs**\n",
      "\n",
      "* Salary and benefits for sworn officers and civilian staff\n",
      "* Number of personnel and staffing levels\n",
      "* Recruitment and retention strategies and their associated costs\n",
      "* Discussion of any notable changes or trends in personnel costs (e.g., increased overtime, hiring freezes)\n",
      "\n",
      "**IV. Operational Expenses**\n",
      "\n",
      "* Overview of operational expenses, including:\n",
      "\t+ Fuel and vehicle maintenance\n",
      "\t+ Equipment and supplies (e.g., firearms, body armor, communication devices)\n",
      "\t+ Facility maintenance and utilities\n",
      "\t+ Travel and training expenses\n",
      "* Discussion of any notable changes or trends in operational expenses (e.g., increased fuel costs, new equipment purchases)\n",
      "\n",
      "**V. Community Policing and Outreach Initiatives**\n",
      "\n",
      "* Overview of community policing and outreach initiatives, including:\n",
      "\t+ Neighborhood policing programs\n",
      "\t+ Youth and community engagement programs\n",
      "\t+ Mental health and crisis response services\n",
      "* Budget allocation for these initiatives and discussion of their effectiveness\n",
      "\n",
      "**VI. Technology and Equipment Upgrades**\n",
      "\n",
      "* Overview of technology and equipment upgrades, including:\n",
      "\t+ Body-worn cameras and other surveillance technology\n",
      "\t+ Communication systems and emergency response infrastructure\n",
      "\t+ Forensic analysis and crime lab equipment\n",
      "* Budget allocation for these upgrades and discussion of their impact on policing and public safety\n",
      "\n",
      "**VII. Challenges and Controversies**\n",
      "\n",
      "* Discussion of challenges and controversies related to the SFPD budget, including:\n",
      "\t+ Funding for police reform and accountability initiatives\n",
      "\t+ Criticisms of police spending and resource allocation\n",
      "\t+ Impact of budget constraints on policing services and community safety\n",
      "\n",
      "**VIII. Conclusion**\n",
      "\n",
      "* Summary of key findings and takeaways from the 2023 SFPD budget\n",
      "* Discussion of implications for public safety and community policing in San Francisco\n",
      "* Final thoughts and recommendations for future budget allocations and policing strategies.\n",
      "\n",
      "To fulfill this outline, the following questions will need to be answered:\n",
      "\n",
      "* What is the total budget allocation for the SFPD in 2023?\n",
      "* How does the 2023 budget compare to previous years' budgets?\n",
      "* What are the major categories of expenditure in the 2023 budget?\n",
      "* What are the personnel costs, including salary and benefits, for sworn officers and civilian staff?\n",
      "* What are the operational expenses, including fuel, equipment, and facility maintenance?\n",
      "* What community policing and outreach initiatives are funded in the 2023 budget?\n",
      "* What technology and equipment upgrades are planned or underway, and what is their budget allocation?\n",
      "* What challenges and controversies are associated with the SFPD budget, and how are they being addressed?\n",
      "\n",
      "These questions will help to gather the necessary facts and information to create a comprehensive and informative blog post on the budget of the San Francisco Police Department in 2023.</outline><question>What are the personnel costs, including salary and benefits, for sworn officers?</question>\n",
      "<answer><function:san_francisco_budget_2023>{\"input\": \"personnel costs for sworn officers\"}</function></answer>\n",
      "<question>How does the 2023 budget compare to the 2022 budget?</question>\n",
      "<answer><function:san_francisco_budget_2023>{\"input\": \"compare 2023 budget to 2022 budget\"}</function></answer>\n",
      "<question>What community policing and outreach initiatives are funded in the 2023 budget?</question>\n",
      "<answer><function:san_francisco_budget_2023>{\"input\": \"community policing and outreach initiatives 2023 budget\"}</function></answer>\n",
      "<question>What is the total budget allocation for the SFPD in 2023?</question>\n",
      "<answer>The total budget allocation for the San Francisco Police Department (SFPD) in 2023 is $776.8 million.</answer>\n",
      "<question>What are the operational expenses, including fuel and vehicle maintenance?</question>\n",
      "<answer>The operational expenses, including fuel and vehicle maintenance, have a budget of $1,088,786,650 for 2024-2025. This category likely encompasses a broad range of expenditures related to the upkeep and operation of vehicles and other equipment, underscoring the organization's ongoing commitment to maintaining its assets and ensuring their continued functionality.</answer>\n",
      "<question>What technology and equipment upgrades are planned or underway?</question>\n",
      "<answer>The City of San Francisco is planning or undertaking various technology and equipment upgrades. These include replacing critical systems, developing new platforms to enhance city services and operations, expanding and optimizing cloud services, improving digital accessibility and inclusion, and developing new applications to enhance the speed, security, performance, and reliability of City services. Additionally, the City is establishing centers of excellence, such as the Cloud Center of Excellence, to help departments leverage technology more effectively and efficiently. The City is also exploring new technologies and solutions to support its goals, including the development of online portals and databases to facilitate resident engagement and access to city services.</answer>\n",
      "<question>What are the major categories of expenditure in the 2023 budget?</question>\n",
      "<answer>The major categories of expenditure in the 2023 budget include citywide expenditures such as voter mandated General Fund support for transit, libraries, and other baselines, the General Fund portion of retiree health premiums, nonprofit cost of doing business increases, required reserve deposits, and debt service. These costs are budgeted in General City Responsibility rather than allocating costs to departments. Additionally, expenditures related to Human Welfare & Neighborhood Development are also significant, including departments such as Children, Youth & Their Families, Child Support Services, Dept of Early Childhood, Environment, Homelessness And Supportive Housing, Human Rights Commission, and Human Services.</answer>\n",
      "<question>What challenges and controversies are associated with the SFPD budget?</question>\n",
      "<answer>The San Francisco Police Department (SFPD) faces significant budget challenges, including recruitment and retention issues, chronic understaffing, and the need to implement reforms and achieve substantial compliance with state laws. The Department must balance competing demands and priorities to ensure effective and responsible use of its budget. Controversies surrounding the SFPD budget may include the use of overtime funding, the implementation of new technologies and systems, and the allocation of resources for community programs and initiatives. The Department's efforts to address issues of trust and accountability within the community may also be a subject of controversy and debate.</answer>\n",
      "\n",
      "Step write_report produced event ReviewEvent\n",
      "Running step review_report\n",
      "Step review_report produced no event\n",
      "Formulated some more questions\n",
      "Running step answer_question\n",
      "> Running step 1515025f-3d98-48ef-82dc-fe1ccb395c95. Step input: What is the exact breakdown of personnel costs, including salary and benefits, for sworn officers in the 2023 SFPD budget?\n",
      "Added user message to memory: What is the exact breakdown of personnel costs, including salary and benefits, for sworn officers in the 2023 SFPD budget?\n",
      "Running step answer_question\n",
      "> Running step 89d8cbfd-decd-4f6e-875c-ee764cc51d57. Step input: What are the specific details and funding allocations for the community policing and outreach initiatives mentioned in the 2023 budget?\n",
      "Added user message to memory: What are the specific details and funding allocations for the community policing and outreach initiatives mentioned in the 2023 budget?\n",
      "Running step answer_question\n",
      "> Running step 78a4965f-1507-4238-8306-62c3e93582e3. Step input: What is the exact figure for operational expenses, including fuel and vehicle maintenance, in the 2023 SFPD budget?\n",
      "Added user message to memory: What is the exact figure for operational expenses, including fuel and vehicle maintenance, in the 2023 SFPD budget?\n",
      "Running step answer_question\n",
      "> Running step ca4c2497-c62c-4fcd-8ae5-4108bfdf0864. Step input: How do the budget allocations for technology and equipment upgrades in 2023 compare to previous years, and what specific upgrades are planned or underway?\n",
      "Added user message to memory: How do the budget allocations for technology and equipment upgrades in 2023 compare to previous years, and what specific upgrades are planned or underway?\n",
      "=== Calling Function ===\n",
      "Calling function: san_francisco_budget_2023 with args: {\"input\": \"community policing and outreach initiatives funding allocations 2023\"}\n",
      "=== Calling Function ===\n",
      "Calling function: san_francisco_budget_2023 with args: {\"input\": \"SFPD personnel costs sworn officers 2023 budget breakdown salary benefits\"}\n",
      "=== LLM Response ===\n",
      "<function:san_francisco_budget_2023>{\"input\": \"technology and equipment upgrades 2023 vs previous years and planned upgrades\"}</function>\n",
      "Step answer_question produced event AnswerEvent\n",
      "=== LLM Response ===\n",
      "<function:san_francisco_budget_2023>{\"input\": \"SFPD operational expenses fuel vehicle maintenance 2023 budget\"}</function>\n",
      "Step answer_question produced event AnswerEvent\n",
      "To question 'How do the budget allocations for technology and equipment upgrades in 2023 compare to previous years, and what specific upgrades are planned or underway?' the agent answered: <function:san_francisco_budget_2023>{\"input\": \"technology and equipment upgrades 2023 vs previous years and planned upgrades\"}</function>\n",
      "To question 'What is the exact figure for operational expenses, including fuel and vehicle maintenance, in the 2023 SFPD budget?' the agent answered: <function:san_francisco_budget_2023>{\"input\": \"SFPD operational expenses fuel vehicle maintenance 2023 budget\"}</function>\n",
      "Running step write_report\n",
      "Step write_report produced no event\n",
      "Running step write_report\n",
      "Step write_report produced no event\n",
      "=== Function Output ===\n",
      "The department's commitment to community policing and outreach initiatives is reflected in the proposed budget for 2023, which includes substantial funding allocations. Specifically, $2.2 million is allocated in FY 2023-24 and $3.0 million in FY 2024-25 to support the expansion of Community Police Service Aides (PSAs) programs. These programs provide a range of support services to sworn officers and help foster positive relationships with the community. Additionally, the budget includes $2.8 million in FY 2023-24 and $2.9 million in FY 2024-25 to support the expansion of ambassador programs, such as the Community Ambassadors program, which aims to build trust and understanding between law enforcement and the communities they serve. Furthermore, $26.5 million is allocated in FY 2023-24 and $16.0 million in FY 2024-25 to support the expansion of Community Safety Ambassadors in key areas throughout the city. These investments underscore the department's dedication to enhancing community outreach and engagement, and to providing additional support services to address community needs, ultimately contributing to a safer and more connected community.\n",
      "> Running step cf1ebb7d-a2d3-4360-b2d9-767859e64103. Step input: None\n",
      "=== LLM Response ===\n",
      "The 2023 budget for San Francisco allocates $2.2 million in FY 2023-24 and $3.0 million in FY 2024-25 to support the expansion of Community Police Service Aides (PSAs) programs, $2.8 million in FY 2023-24 and $2.9 million in FY 2024-25 to support the expansion of ambassador programs, and $26.5 million in FY 2023-24 and $16.0 million in FY 2024-25 to support the expansion of Community Safety Ambassadors. These investments aim to enhance community outreach and engagement, and provide additional support services to address community needs, ultimately contributing to a safer and more connected community.\n",
      "Step answer_question produced event AnswerEvent\n",
      "To question 'What are the specific details and funding allocations for the community policing and outreach initiatives mentioned in the 2023 budget?' the agent answered: The 2023 budget for San Francisco allocates $2.2 million in FY 2023-24 and $3.0 million in FY 2024-25 to support the expansion of Community Police Service Aides (PSAs) programs, $2.8 million in FY 2023-24 and $2.9 million in FY 2024-25 to support the expansion of ambassador programs, and $26.5 million in FY 2023-24 and $16.0 million in FY 2024-25 to support the expansion of Community Safety Ambassadors. These investments aim to enhance community outreach and engagement, and provide additional support services to address community needs, ultimately contributing to a safer and more connected community.\n",
      "Running step write_report\n",
      "Step write_report produced no event\n",
      "=== Function Output ===\n",
      "The Sheriff's Office budget for FY 2023-24 is $291.7 million, which is 2.5 percent lower than the FY 2022-23 budget. This decrease is primarily due to salary reductions from position vacancies and a decrease in overtime. The proposed budget for FY 2024-25 is $293.7 million, which is 0.7 percent higher than the FY 2023-24 proposed budget, mainly due to increases in interdepartmental services and salaries and benefits.\n",
      "\n",
      "In terms of personnel costs, the Sheriff's Office is facing ongoing staffing challenges, resulting in a demand for overtime to meet mandated minimum staffing requirements. The proposed budget includes funding to meet the overtime needs of the Sheriff's Office in FY 2023-24. As the Office improves its regular staffing levels, the need for overtime spending will decrease.\n",
      "\n",
      "The Sheriff's Office is aggressively recruiting to fill numerous vacancies in its deputy sheriff positions and professional staff. The Office is also increasing its law enforcement presence in the community, expanding the field officer training program, and increasing staff in the warrant services unit.\n",
      "\n",
      "Regarding labor negotiations, the Employee Relations Division is responsible for negotiating all non-Municipal Transportation Agency labor contracts for City employees. In FY 2023-24, the Division will be negotiating collective bargaining agreements on behalf of 88 percent of the City's workforce covered by 34 union contracts.\n",
      "\n",
      "The City is also self-insuring for workers' compensation and is financially responsible for all workers' compensation liabilities. The Workers' Compensation Division will continue to advance its safety and health initiatives and partner with departments to implement the Temporary Transitional Work Assignment policy to improve Return to Work outcomes.\n",
      "\n",
      "The Mayor's proposed budget includes funding for the new Career Center at City Hall, which will help City employees access existing programs and resources that support their career goals. The Department will also launch and promote new career pathway programs, including a public safety pathway program and a health worker pathway program.\n",
      "\n",
      "The San Francisco Health Service System (SFHSS) is dedicated to preserving and improving sustainable, quality health benefits and enhancing the well-being of employees, retirees, and their families. The proposed FY 2023-24 budget for SFHSS is $13.9 million, which is 2.3 percent higher than the FY 2022-23 budget, due to enhanced Employee Assistance services and an increase in a work order with the Human Resources Department.\n",
      "\n",
      "SFHSS has completed its 2023-25 strategic plan, which includes strategic goals to foster equity, advance primary care practice, provide affordable and sustainable healthcare, and support the mental health and well-being of its membership. The SFHSS medical rates trend vs benchmarks shows that the rising cost of healthcare has outpaced inflation in most years, but SFHSS oversight has resulted in lower increases than the national average and inflation for four of the last five years.\n",
      "> Running step cc8562aa-15ae-4a56-8bf9-54f6c8e976c9. Step input: None\n",
      "=== LLM Response ===\n",
      "The exact breakdown of personnel costs, including salary and benefits, for sworn officers in the 2023 SFPD budget is not explicitly stated in the provided information. However, the Sheriff's Office budget for FY 2023-24 is $291.7 million, which includes funding for personnel costs such as salaries and benefits. The proposed budget for FY 2024-25 is $293.7 million, which is 0.7 percent higher than the FY 2023-24 proposed budget, mainly due to increases in interdepartmental services and salaries and benefits.\n",
      "Step answer_question produced event AnswerEvent\n",
      "To question 'What is the exact breakdown of personnel costs, including salary and benefits, for sworn officers in the 2023 SFPD budget?' the agent answered: The exact breakdown of personnel costs, including salary and benefits, for sworn officers in the 2023 SFPD budget is not explicitly stated in the provided information. However, the Sheriff's Office budget for FY 2023-24 is $291.7 million, which includes funding for personnel costs such as salaries and benefits. The proposed budget for FY 2024-25 is $293.7 million, which is 0.7 percent higher than the FY 2023-24 proposed budget, mainly due to increases in interdepartmental services and salaries and benefits.\n",
      "Running step write_report\n",
      "Writing report with prompt:\n",
      "You are an expert at writing blog posts. You are given an outline of a blog post\n",
      "        and a series of questions and answers that should provide all the data you need to write the\n",
      "        blog post. Compose the blog post according to the outline, using only the data given in the\n",
      "        answers. The outline is in <outline> and the questions and answers are in <questions> and\n",
      "        <answers>.\n",
      "        <outline>Here is a detailed outline for the blog post on the budget of the San Francisco Police Department in 2023:\n",
      "\n",
      "**I. Introduction**\n",
      "\n",
      "* Brief overview of the San Francisco Police Department (SFPD) and its role in the city\n",
      "* Importance of understanding the budget of the SFPD\n",
      "* Thesis statement: The 2023 budget of the San Francisco Police Department is a critical component of the city's public safety strategy, and understanding its allocation and priorities is essential for ensuring effective policing and community safety.\n",
      "\n",
      "**II. Overview of the 2023 Budget**\n",
      "\n",
      "* Total budget allocation for the SFPD in 2023\n",
      "* Comparison to previous years' budgets (e.g., 2022, 2021)\n",
      "* Breakdown of the budget into major categories (e.g., personnel, operations, equipment, training)\n",
      "\n",
      "**III. Personnel Costs**\n",
      "\n",
      "* Salary and benefits for sworn officers and civilian staff\n",
      "* Number of personnel and staffing levels\n",
      "* Recruitment and retention strategies and their associated costs\n",
      "* Discussion of any notable changes or trends in personnel costs (e.g., increased overtime, hiring freezes)\n",
      "\n",
      "**IV. Operational Expenses**\n",
      "\n",
      "* Overview of operational expenses, including:\n",
      "\t+ Fuel and vehicle maintenance\n",
      "\t+ Equipment and supplies (e.g., firearms, body armor, communication devices)\n",
      "\t+ Facility maintenance and utilities\n",
      "\t+ Travel and training expenses\n",
      "* Discussion of any notable changes or trends in operational expenses (e.g., increased fuel costs, new equipment purchases)\n",
      "\n",
      "**V. Community Policing and Outreach Initiatives**\n",
      "\n",
      "* Overview of community policing and outreach initiatives, including:\n",
      "\t+ Neighborhood policing programs\n",
      "\t+ Youth and community engagement programs\n",
      "\t+ Mental health and crisis response services\n",
      "* Budget allocation for these initiatives and discussion of their effectiveness\n",
      "\n",
      "**VI. Technology and Equipment Upgrades**\n",
      "\n",
      "* Overview of technology and equipment upgrades, including:\n",
      "\t+ Body-worn cameras and other surveillance technology\n",
      "\t+ Communication systems and emergency response infrastructure\n",
      "\t+ Forensic analysis and crime lab equipment\n",
      "* Budget allocation for these upgrades and discussion of their impact on policing and public safety\n",
      "\n",
      "**VII. Challenges and Controversies**\n",
      "\n",
      "* Discussion of challenges and controversies related to the SFPD budget, including:\n",
      "\t+ Funding for police reform and accountability initiatives\n",
      "\t+ Criticisms of police spending and resource allocation\n",
      "\t+ Impact of budget constraints on policing services and community safety\n",
      "\n",
      "**VIII. Conclusion**\n",
      "\n",
      "* Summary of key findings and takeaways from the 2023 SFPD budget\n",
      "* Discussion of implications for public safety and community policing in San Francisco\n",
      "* Final thoughts and recommendations for future budget allocations and policing strategies.\n",
      "\n",
      "To fulfill this outline, the following questions will need to be answered:\n",
      "\n",
      "* What is the total budget allocation for the SFPD in 2023?\n",
      "* How does the 2023 budget compare to previous years' budgets?\n",
      "* What are the major categories of expenditure in the 2023 budget?\n",
      "* What are the personnel costs, including salary and benefits, for sworn officers and civilian staff?\n",
      "* What are the operational expenses, including fuel, equipment, and facility maintenance?\n",
      "* What community policing and outreach initiatives are funded in the 2023 budget?\n",
      "* What technology and equipment upgrades are planned or underway, and what is their budget allocation?\n",
      "* What challenges and controversies are associated with the SFPD budget, and how are they being addressed?\n",
      "\n",
      "These questions will help to gather the necessary facts and information to create a comprehensive and informative blog post on the budget of the San Francisco Police Department in 2023.</outline><question>What are the personnel costs, including salary and benefits, for sworn officers?</question>\n",
      "<answer><function:san_francisco_budget_2023>{\"input\": \"personnel costs for sworn officers\"}</function></answer>\n",
      "<question>How does the 2023 budget compare to the 2022 budget?</question>\n",
      "<answer><function:san_francisco_budget_2023>{\"input\": \"compare 2023 budget to 2022 budget\"}</function></answer>\n",
      "<question>What community policing and outreach initiatives are funded in the 2023 budget?</question>\n",
      "<answer><function:san_francisco_budget_2023>{\"input\": \"community policing and outreach initiatives 2023 budget\"}</function></answer>\n",
      "<question>What is the total budget allocation for the SFPD in 2023?</question>\n",
      "<answer>The total budget allocation for the San Francisco Police Department (SFPD) in 2023 is $776.8 million.</answer>\n",
      "<question>What are the operational expenses, including fuel and vehicle maintenance?</question>\n",
      "<answer>The operational expenses, including fuel and vehicle maintenance, have a budget of $1,088,786,650 for 2024-2025. This category likely encompasses a broad range of expenditures related to the upkeep and operation of vehicles and other equipment, underscoring the organization's ongoing commitment to maintaining its assets and ensuring their continued functionality.</answer>\n",
      "<question>What technology and equipment upgrades are planned or underway?</question>\n",
      "<answer>The City of San Francisco is planning or undertaking various technology and equipment upgrades. These include replacing critical systems, developing new platforms to enhance city services and operations, expanding and optimizing cloud services, improving digital accessibility and inclusion, and developing new applications to enhance the speed, security, performance, and reliability of City services. Additionally, the City is establishing centers of excellence, such as the Cloud Center of Excellence, to help departments leverage technology more effectively and efficiently. The City is also exploring new technologies and solutions to support its goals, including the development of online portals and databases to facilitate resident engagement and access to city services.</answer>\n",
      "<question>What are the major categories of expenditure in the 2023 budget?</question>\n",
      "<answer>The major categories of expenditure in the 2023 budget include citywide expenditures such as voter mandated General Fund support for transit, libraries, and other baselines, the General Fund portion of retiree health premiums, nonprofit cost of doing business increases, required reserve deposits, and debt service. These costs are budgeted in General City Responsibility rather than allocating costs to departments. Additionally, expenditures related to Human Welfare & Neighborhood Development are also significant, including departments such as Children, Youth & Their Families, Child Support Services, Dept of Early Childhood, Environment, Homelessness And Supportive Housing, Human Rights Commission, and Human Services.</answer>\n",
      "<question>What challenges and controversies are associated with the SFPD budget?</question>\n",
      "<answer>The San Francisco Police Department (SFPD) faces significant budget challenges, including recruitment and retention issues, chronic understaffing, and the need to implement reforms and achieve substantial compliance with state laws. The Department must balance competing demands and priorities to ensure effective and responsible use of its budget. Controversies surrounding the SFPD budget may include the use of overtime funding, the implementation of new technologies and systems, and the allocation of resources for community programs and initiatives. The Department's efforts to address issues of trust and accountability within the community may also be a subject of controversy and debate.</answer>\n",
      "<question>How do the budget allocations for technology and equipment upgrades in 2023 compare to previous years, and what specific upgrades are planned or underway?</question>\n",
      "<answer><function:san_francisco_budget_2023>{\"input\": \"technology and equipment upgrades 2023 vs previous years and planned upgrades\"}</function></answer>\n",
      "<question>What is the exact figure for operational expenses, including fuel and vehicle maintenance, in the 2023 SFPD budget?</question>\n",
      "<answer><function:san_francisco_budget_2023>{\"input\": \"SFPD operational expenses fuel vehicle maintenance 2023 budget\"}</function></answer>\n",
      "<question>What are the specific details and funding allocations for the community policing and outreach initiatives mentioned in the 2023 budget?</question>\n",
      "<answer>The 2023 budget for San Francisco allocates $2.2 million in FY 2023-24 and $3.0 million in FY 2024-25 to support the expansion of Community Police Service Aides (PSAs) programs, $2.8 million in FY 2023-24 and $2.9 million in FY 2024-25 to support the expansion of ambassador programs, and $26.5 million in FY 2023-24 and $16.0 million in FY 2024-25 to support the expansion of Community Safety Ambassadors. These investments aim to enhance community outreach and engagement, and provide additional support services to address community needs, ultimately contributing to a safer and more connected community.</answer>\n",
      "<question>What is the exact breakdown of personnel costs, including salary and benefits, for sworn officers in the 2023 SFPD budget?</question>\n",
      "<answer>The exact breakdown of personnel costs, including salary and benefits, for sworn officers in the 2023 SFPD budget is not explicitly stated in the provided information. However, the Sheriff's Office budget for FY 2023-24 is $291.7 million, which includes funding for personnel costs such as salaries and benefits. The proposed budget for FY 2024-25 is $293.7 million, which is 0.7 percent higher than the FY 2023-24 proposed budget, mainly due to increases in interdepartmental services and salaries and benefits.</answer>\n",
      "\n",
      "Step write_report produced event ReviewEvent\n",
      "Running step review_report\n",
      "Step review_report produced event StopEvent\n",
      "Blog post is fine\n",
      "------- Blog post ----------\n",
      " **The 2023 Budget of the San Francisco Police Department: Understanding Allocation and Priorities**\n",
      "\n",
      "The San Francisco Police Department (SFPD) plays a vital role in maintaining public safety and order in the city of San Francisco. As such, understanding the budget of the SFPD is crucial for ensuring effective policing and community safety. The 2023 budget of the SFPD is a critical component of the city's public safety strategy, and this blog post aims to provide an overview of the budget allocation and priorities.\n",
      "\n",
      "**Overview of the 2023 Budget**\n",
      "\n",
      "The total budget allocation for the SFPD in 2023 is $776.8 million. Compared to the 2022 budget, the 2023 budget has increased, although the exact percentage increase is not specified. The major categories of expenditure in the 2023 budget include citywide expenditures such as voter-mandated General Fund support for transit, libraries, and other baselines, as well as expenditures related to Human Welfare & Neighborhood Development.\n",
      "\n",
      "**Personnel Costs**\n",
      "\n",
      "The personnel costs, including salary and benefits, for sworn officers in the 2023 SFPD budget are not explicitly stated. However, the Sheriff's Office budget for FY 2023-24 is $291.7 million, which includes funding for personnel costs such as salaries and benefits. The proposed budget for FY 2024-25 is $293.7 million, which is 0.7 percent higher than the FY 2023-24 proposed budget, mainly due to increases in interdepartmental services and salaries and benefits.\n",
      "\n",
      "**Operational Expenses**\n",
      "\n",
      "The operational expenses, including fuel and vehicle maintenance, have a significant budget allocation. Although the exact figure for the 2023 SFPD budget is not provided, the operational expenses for 2024-2025 have a budget of $1,088,786,650. This category likely encompasses a broad range of expenditures related to the upkeep and operation of vehicles and other equipment.\n",
      "\n",
      "**Community Policing and Outreach Initiatives**\n",
      "\n",
      "The 2023 budget allocates significant funding to support community policing and outreach initiatives. Specifically, the budget allocates $2.2 million in FY 2023-24 and $3.0 million in FY 2024-25 to support the expansion of Community Police Service Aides (PSAs) programs, $2.8 million in FY 2023-24 and $2.9 million in FY 2024-25 to support the expansion of ambassador programs, and $26.5 million in FY 2023-24 and $16.0 million in FY 2024-25 to support the expansion of Community Safety Ambassadors. These investments aim to enhance community outreach and engagement, and provide additional support services to address community needs.\n",
      "\n",
      "**Technology and Equipment Upgrades**\n",
      "\n",
      "The City of San Francisco is planning or undertaking various technology and equipment upgrades, including replacing critical systems, developing new platforms to enhance city services and operations, expanding and optimizing cloud services, improving digital accessibility and inclusion, and developing new applications to enhance the speed, security, performance, and reliability of City services. Although the exact budget allocation for these upgrades is not specified, these initiatives aim to support the city's goals and improve policing and public safety.\n",
      "\n",
      "**Challenges and Controversies**\n",
      "\n",
      "The SFPD faces significant budget challenges, including recruitment and retention issues, chronic understaffing, and the need to implement reforms and achieve substantial compliance with state laws. The Department must balance competing demands and priorities to ensure effective and responsible use of its budget. Controversies surrounding the SFPD budget may include the use of overtime funding, the implementation of new technologies and systems, and the allocation of resources for community programs and initiatives.\n",
      "\n",
      "**Conclusion**\n",
      "\n",
      "In conclusion, the 2023 budget of the San Francisco Police Department is a critical component of the city's public safety strategy. Understanding the budget allocation and priorities is essential for ensuring effective policing and community safety. The budget allocates significant funding to support community policing and outreach initiatives, technology and equipment upgrades, and personnel costs. However, the SFPD also faces significant budget challenges and controversies, which must be addressed to ensure the effective and responsible use of its budget. As the city continues to evolve and grow, it is essential to prioritize public safety and ensure that the SFPD has the necessary resources to maintain order and protect the community.\n"
     ]
    }
   ],
   "source": [
    "agent = DocumentResearchAgent(timeout=600, verbose=True)\n",
    "handler = agent.run(\n",
    "    query=\"Tell me about the budget of the San Francisco Police Department in 2023\",\n",
    "    tools=[budget_tool],\n",
    ")\n",
    "async for ev in handler.stream_events():\n",
    "    if isinstance(ev, ProgressEvent):\n",
    "        print(ev.progress)\n",
    "final_result = await handler\n",
    "print(\"------- Blog post ----------\\n\", final_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sample output rendered as markdown\n",
    "\n",
    "We've taken the output of the agent and rendered it here:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**The 2023 Budget of the San Francisco Police Department: Understanding Allocation and Priorities**\n",
    "\n",
    "The San Francisco Police Department (SFPD) plays a vital role in maintaining public safety and order in the city of San Francisco. As such, understanding the budget of the SFPD is crucial for ensuring effective policing and community safety. The 2023 budget of the SFPD is a critical component of the city's public safety strategy, and this blog post aims to provide an overview of the budget allocation and priorities.\n",
    "\n",
    "**Overview of the 2023 Budget**\n",
    "\n",
    "The total budget allocation for the SFPD in 2023 is $776.8 million. Compared to the 2022 budget, the 2023 budget has increased, although the exact percentage increase is not specified. The major categories of expenditure in the 2023 budget include citywide expenditures such as voter-mandated General Fund support for transit, libraries, and other baselines, as well as expenditures related to Human Welfare & Neighborhood Development.\n",
    "\n",
    "**Personnel Costs**\n",
    "\n",
    "The personnel costs, including salary and benefits, for sworn officers in the 2023 SFPD budget are not explicitly stated. However, the Sheriff's Office budget for FY 2023-24 is $291.7 million, which includes funding for personnel costs such as salaries and benefits. The proposed budget for FY 2024-25 is $293.7 million, which is 0.7 percent higher than the FY 2023-24 proposed budget, mainly due to increases in interdepartmental services and salaries and benefits.\n",
    "\n",
    "**Operational Expenses**\n",
    "\n",
    "The operational expenses, including fuel and vehicle maintenance, have a significant budget allocation. Although the exact figure for the 2023 SFPD budget is not provided, the operational expenses for 2024-2025 have a budget of $1,088,786,650. This category likely encompasses a broad range of expenditures related to the upkeep and operation of vehicles and other equipment.\n",
    "\n",
    "**Community Policing and Outreach Initiatives**\n",
    "\n",
    "The 2023 budget allocates significant funding to support community policing and outreach initiatives. Specifically, the budget allocates $2.2 million in FY 2023-24 and $3.0 million in FY 2024-25 to support the expansion of Community Police Service Aides (PSAs) programs, $2.8 million in FY 2023-24 and $2.9 million in FY 2024-25 to support the expansion of ambassador programs, and $26.5 million in FY 2023-24 and $16.0 million in FY 2024-25 to support the expansion of Community Safety Ambassadors. These investments aim to enhance community outreach and engagement, and provide additional support services to address community needs.\n",
    "\n",
    "**Technology and Equipment Upgrades**\n",
    "\n",
    "The City of San Francisco is planning or undertaking various technology and equipment upgrades, including replacing critical systems, developing new platforms to enhance city services and operations, expanding and optimizing cloud services, improving digital accessibility and inclusion, and developing new applications to enhance the speed, security, performance, and reliability of City services. Although the exact budget allocation for these upgrades is not specified, these initiatives aim to support the city's goals and improve policing and public safety.\n",
    "\n",
    "**Challenges and Controversies**\n",
    "\n",
    "The SFPD faces significant budget challenges, including recruitment and retention issues, chronic understaffing, and the need to implement reforms and achieve substantial compliance with state laws. The Department must balance competing demands and priorities to ensure effective and responsible use of its budget. Controversies surrounding the SFPD budget may include the use of overtime funding, the implementation of new technologies and systems, and the allocation of resources for community programs and initiatives.\n",
    "\n",
    "**Conclusion**\n",
    "\n",
    "In conclusion, the 2023 budget of the San Francisco Police Department is a critical component of the city's public safety strategy. Understanding the budget allocation and priorities is essential for ensuring effective policing and community safety. The budget allocates significant funding to support community policing and outreach initiatives, technology and equipment upgrades, and personnel costs. However, the SFPD also faces significant budget challenges and controversies, which must be addressed to ensure the effective and responsible use of its budget. As the city continues to evolve and grow, it is essential to prioritize public safety and ensure that the SFPD has the necessary resources to maintain order and protect the community."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Agentic strategies produce better results\n",
    "\n",
    "As you can see in the output, the agent attempts to fulfill the request with an initial set of questions and answers, decides it needs more input, and asks more questions before settling on the final result. This ability to self-reflect and improve is part of why agentic strategies are such a powerful way to improve the quality of generative AI output."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
